package zheezes.protocol.impl.gbw.format;

import java.util.Calendar;

import zheezes.util.ByteUtil;
import zheezes.util.IntUtil;


public class DateFormat {
	public static final void set(Calendar cal, int field, byte value) {
		int val = 0;
		switch (field) {
		case Calendar.MONTH:
			val = ByteUtil.bcdToBin(value) - 1;
			break;
		case Calendar.YEAR:
			val = IntUtil.cutLow(cal.get(Calendar.YEAR), 2) + ByteUtil.bcdToBin(value);
			break;
		default:
			val = ByteUtil.bcdToBin(value);
		}
		cal.set(field, val);
	}

	public static final byte get(Calendar cal, int field) {
		byte bin = 0x00;
		switch (field) {
		case Calendar.DAY_OF_WEEK:
			byte week = (byte) cal.get(Calendar.DAY_OF_WEEK);
			if (week == Calendar.SUNDAY) {
				week = 7;
			} else {
				week--;
			}
			bin = week;
			break;
		case Calendar.MONTH:
			bin = (byte) (cal.get(Calendar.MONDAY) + 1);
			break;
		case Calendar.YEAR:
			bin = ByteUtil.binToBcd((byte) (cal.get(Calendar.YEAR) % 100));
			break;
		default:
			bin = (byte) cal.get(field);
		}

		return ByteUtil.binToBcd(bin);
	}
}
